import 'dart:async';

import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainSetModel.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

class MainChangeiPhonePage extends StatefulWidget {
  MainChangeiPhonePage({Key key}) : super(key: key);

  @override
  _MainChangeiPhonePageState createState() => _MainChangeiPhonePageState();
}

class _MainChangeiPhonePageState extends State<MainChangeiPhonePage> {
  String yzmText = "发送验证码";
  Timer countDownTimer;

  final mobileText01 = TextEditingController();
  final codeText = TextEditingController();
  MainSetModel mainSetModel;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    uploadSet();
  }

  void uploadSet() {
    DioUtils.noTokenPostHttp(
      context,
      "Usercommon/app_config",
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (mounted) {
            setState(() {
              mainSetModel = MainSetModel.fromJson(t);
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("修改手机号"),
        centerTitle: true,
        elevation: 0,
        leading: IconButton(
          icon: Image.asset(
            "images/MainBackImage.png",
            height: 20,
            width: 20,
            color: Colors.black,
          ),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          InkWell(
            child: Container(
              padding: EdgeInsets.only(right: 8),
              height: setHeight(88),
              // width: setWidth(100),
              alignment: Alignment.center,
              child: Text(
                "联系客服",
                style: TextStyle(color: maincolor, fontSize: setFontSize(28)),
              ),
            ),
            onTap: () {
              print("object");
              launch("tel://${mainSetModel.data.csMobile}");
            },
          )
        ],
      ),
      body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: mainView()),
    );
  }

  Widget mainView() {
    return ListView(
      children: [
        Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              padding: EdgeInsets.all(20),
              child: Column(
                children: [
                  mobileView01(),
                  lineView(),
                  SizedBox(height: setHeight(10)),
                  codeView(),
                  lineView(),
                  SizedBox(height: setHeight(60)),
                  loginView(),
                  SizedBox(height: setHeight(40)),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget lineView() {
    return Container(
      height: 1,
      color: Color(0xFFEDEDED),
    );
  }

  Text textview01(String text) {
    return Text(
      text,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(28),
      ),
    );
  }

  TextStyle hintStyle() {
    return TextStyle(
      fontSize: setFontSize(32),
      color: Color(0xFFCBCBCB),
    );
  }

  TextStyle textStyle() {
    return TextStyle(
      fontSize: setFontSize(32),
      color: Color(0xFF333333),
    );
  }

  Widget mobileView01() {
    return Container(
      child: Row(
        children: [
          textview01("手机号:"),
          SizedBox(width: 10),
          Expanded(
              child: TextField(
            controller: mobileText01,
            textAlign: TextAlign.start,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "请输入手机号",
                hintStyle: hintStyle()),
            style: textStyle(),
          )),
          Container(
            child: OutlineButton(
              onPressed: yzmText == "发送验证码" ? getCode : null,
              padding: EdgeInsets.only(left: 8, right: 8),
              borderSide: BorderSide(color: maincolor),
              highlightedBorderColor: maincolor,
              child: Text(yzmText),
              textColor: maincolor,
            ),
          ),
          SizedBox(width: setWidth(4)),
        ],
      ),
    );
  }

  void getCode() {
    DioUtils.postHttp(
      context,
      "user/send_code",
      parameters: {
        "user_type": getData("AppType"),
        "mobile": mobileText01.text,
        "event": "changemobile",
      },
      onSuccess: (t) {
        if (t["code"].toString() == "1") {
          // ignore: unnecessary_statements
          yzmText == "发送验证码" ? codeGet() : null;
        }
        showToast(t["msg"]);
      },
      onError: (error) {
        print("$error");
      },
    );
  }

  void codeGet() {
    countDownTimer?.cancel(); //如果已存在先取消置空
    countDownTimer = null;
    countDownTimer = Timer.periodic(Duration(seconds: 1), (t) {
      if (mounted) {
        setState(() {
          if (60 - t.tick > 0) {
            //60-t.tick代表剩余秒数，如果大于0，设置yzmText为剩余秒数，否则重置yzmText，关闭countTimer
            // yzmText = "(${60 - t.tick}s)后请重试";
            yzmText = "${60 - t.tick}秒";
          } else {
            yzmText = '发送验证码';
            countDownTimer.cancel();
            countDownTimer = null;
          }
        });
      }
    });
  }

  Widget codeView() {
    return Container(
      color: Colors.white,
      // padding: EdgeInsets.only(left: 20, right: 20),
      child: Row(
        children: [
          textview01("验证码:"),
          SizedBox(width: 10),
          Expanded(
              child: TextField(
            controller: codeText,
            textAlign: TextAlign.start,
            keyboardType: TextInputType.number,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "请输入短信验证码",
                hintStyle: hintStyle()),
            style: textStyle(),
          )),
        ],
      ),
    );
  }

  Widget loginView() {
    return InkWell(
      child: Container(
        alignment: Alignment.center,
        width: 900,
        height: setHeight(100),
        decoration: BoxDecoration(
          color: maincolor,
          borderRadius: BorderRadius.all(
            Radius.circular(setHeight(10)),
          ),
        ),
        child: Text(
          "验证并继续",
          style: TextStyle(color: Colors.white, fontSize: setFontSize(34)),
        ),
      ),
      onTap: () {
        codeLogin();
      },
    );
  }

  void codeLogin() {
    if (!isPhone(mobileText01.text)) {
      showToast("请输入正确的手机号");
      return;
    }
    if (codeText.text.length == 0) {
      showToast("请输入验证");
      return;
    }
    showLoading(context);
    DioUtils.postHttp(
      context,
      "Usercenter/change_mobile",
      parameters: {
        "token": getData("token"),
        "mobile": mobileText01.text,
        "code": codeText.text,
      },
      onSuccess: (t) {
        dismissLoading(context);
      },
      onError: (error) {
        dismissLoading(context);
        print("$error");
      },
    );
  }
}
